package translinkApp.Data.Utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import translinkApp.Utilities.EmailContent;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;

public class Functions {
	public static String StripAllHtml(String original) {
		String newString = StripHtml(original);
		newString = RemovesSpaces(newString);
		newString = newString.trim();

		return newString;

	}

	public static boolean isParsableToInt(String i) {
		try {
			Integer.parseInt(i);

			return true;
		}

		catch (NumberFormatException nfe) {
			return false;
		}

	}

	public static String removeWords(String initialString, int words) {
		int whiteSpaceCount = 0;
		int index = 0;
		for (char chara : initialString.toCharArray()) {
			if (whiteSpaceCount == words) {
				break;
			}

			if (chara == ' ') {
				whiteSpaceCount++;
			}

			index++;
		}

		return initialString.substring(index);
	}

	public static String[] GetRegex(String regex, String source, boolean multiLined) {

		ArrayList<String> regexValues = new ArrayList<String>();

		Pattern pattern = Pattern.compile(regex);

		if (multiLined) {
			pattern = Pattern.compile(regex, Pattern.DOTALL);
		}

		Matcher matcher = pattern.matcher(source);

		while (matcher.find()) {
			try {
				regexValues.add(matcher.group(1));
			} catch (Exception e) {
				regexValues.add(matcher.group());
			}

		}

		return regexValues.toArray(new String[0]);
	}

	public static String[] GetRegex(String regex, String source, int numGroups, boolean multiLined) {

		ArrayList<String> regexValues = new ArrayList<String>();

		Pattern pattern = Pattern.compile(regex);
		if (multiLined) {
			pattern = Pattern.compile(regex, Pattern.DOTALL);
		}

		Matcher matcher = pattern.matcher(source);

		while (matcher.find()) {
			for (int i = 0; i < numGroups; i++) {
				regexValues.add(matcher.group(i + 1));
			}

		}

		return regexValues.toArray(new String[0]);
	}

	public static String[] GetRegexSingleLine(String regex, String source, int numGroups) {

		ArrayList<String> regexValues = new ArrayList<String>(numGroups);

		Pattern pattern = Pattern.compile(regex);

		Matcher matcher = pattern.matcher(source);

		while (matcher.find()) {
			for (int i = 0; i < numGroups; i++) {
				regexValues.add(matcher.group(i + 1));
			}

		}

		return regexValues.toArray(new String[0]);
	}

	public static int StringInstanceCount(String text, String phrase) {
		int indexLocation = 0;
		int count = 0;

		while (indexLocation != -1) {

			indexLocation = text.indexOf(phrase, indexLocation + 1);

			if (indexLocation != -1) {
				count++;
			}

		}

		return count;
	}

	public static String RemovesSpaces(String original) {

		char[] array = original.toCharArray();

		boolean space = false;
		StringBuilder newString = new StringBuilder();

		for (char ch : array) {
			if (ch == ' ') {
				if (!space) {

					space = true;

				} else {
					continue;
				}
			} else {
				space = false;

			}

			newString.append(ch);

		}
		return newString.toString();
	}

	public static String StripHtml(String original) {
		return original.replace("\n", "").replaceAll("&nbsp;", " ").replaceAll("\t", " ")
				.replace("\r", "");
	}

	/**
	 * Gets file data from a specified text file.
	 * 
	 * @param filePath
	 *            The path to the text file.
	 * @return The data contained within the text file.
	 * @throws IOException
	 */
	public static String getFileData(String filePath) throws IOException {
		FileReader file = new FileReader(filePath);
		BufferedReader reader = new BufferedReader(file);

		String data = "";
		String line = null;

		// Read all of the data into a string, with line breaks.
		while ((line = reader.readLine()) != null) {
			data += line + "\n";
		}

		return data;
	}

	public static Object[] GetCellDetails(String urlSource, int latestIndex, String keyword) {
		latestIndex = urlSource.indexOf(keyword, latestIndex);

		Object[] data = FindBetweenPointAndTag(urlSource, latestIndex, ">", "</td>");
		String distance = (String) data[0];
		latestIndex = ((Number) data[1]).intValue();

		distance = Functions.StripAllHtml(distance);

		Object[] array = new Object[] { distance, latestIndex };
		return array;
	}

	public static Object[] FindBetweenPointAndTag(String original, int currentIndex,
			String startTag, String endTag) {
		int startIndex = original.indexOf(startTag, currentIndex);
		int endIndex = original.indexOf(endTag, startIndex);

		if (startIndex > -1 && endIndex > -1) {
			String newString = original.substring(startIndex + startTag.length(), endIndex);
			newString = Functions.StripAllHtml(newString);

			Object[] array = new Object[] { newString, endIndex + endTag.length() };
			return array;
		}
		return new Object[] { "", -1 };
	}

	public static Object[] FindBoldedData(String original, int latestIndex) {
		String tag = "<b>";
		String endTag = "</b>";

		return FindBetweenPointAndTag(original, latestIndex, tag, endTag);
	}

	/**
	 * Gets the html source code for a specified Url
	 * 
	 * @param urlLink
	 *            The http link to get the source from.
	 * @return Returns a string which contains the entire source code, separated with newline
	 *         characters.
	 * @throws IOException
	 */
	public static String getUrlSource(String urlLink) {

		URL updateURL = null;
		try {
			urlLink = urlLink.replace(" ", "+");
			urlLink = urlLink.replace("[", "%5b");
			urlLink = urlLink.replace("]", "%5d");
			updateURL = new URL(urlLink);
		} catch (MalformedURLException e) {

			e.printStackTrace();
		}

		URLConnection conn = null;
		try {
			conn = updateURL.openConnection();
		} catch (IOException e) {

			e.printStackTrace();
		}//
		InputStream is = null;
		try {
			is = conn.getInputStream();
		} catch (IOException e) {

			e.printStackTrace();
		}
		BufferedInputStream bis = new BufferedInputStream(is);
		ArrayList<Byte> baf = new ArrayList<Byte>();

		int current = 0;
		try {
			while ((current = bis.read()) != -1) {
				baf.add((byte) current);
			}
		} catch (IOException e) {

			e.printStackTrace();
		}

		byte[] byteArray = new byte[baf.size()];
		for (int currentByte = 0; currentByte < baf.size(); currentByte++) {
			byteArray[currentByte] = baf.get(currentByte);
		}
		/* Convert the Bytes read to a String. */
		return new String(byteArray);
	}

	public static InputStream getUrlStream(String urlLink) {

		URL updateURL = null;
		try {
			urlLink = urlLink.replace(" ", "+");
			urlLink = urlLink.replace("[", "%5b");
			urlLink = urlLink.replace("]", "%5d");
			updateURL = new URL(urlLink);
		} catch (MalformedURLException e) {

			e.printStackTrace();
		}

		URLConnection conn = null;
		try {
			conn = updateURL.openConnection();
		} catch (IOException e) {

			e.printStackTrace();
		}//
			// InputStream is = null;
		try {
			return conn.getInputStream();
		} catch (IOException e) {

			return null;
		}
	}

	public static void composeEmail(Context c, EmailContent content) {
		Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);

		emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
				new String[] { content.getSendAddress() });
		emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, content.getSubject());

		emailIntent.setType("plain/text");
		emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, content.getBody());

		c.startActivity(Intent.createChooser(emailIntent, "Send your email in:"));
	}

	public static String getFirstStreet(Context c, Location location) throws IOException {

		if (location == null) {
			return "";
		}

		Geocoder geoCoder = new Geocoder(c);
		List<Address> addresses = null;
		try {
			addresses = geoCoder
					.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

			Address address = addresses.get(0);

			String streetName = address.getAddressLine(0);
			streetName = ParseAddress.modifyAddress(streetName);

			String suburbLine = address.getAddressLine(1);
			suburbLine = new StringBuffer(suburbLine).reverse().toString();

			suburbLine = Functions.removeWords(suburbLine, 2);

			suburbLine = new StringBuffer(suburbLine).reverse().toString();

			return streetName + ", " + suburbLine;
		} catch (IOException e) {
			throw e;
		}
	}

}
